<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/zepto/1.1.6/zepto.min.js"></script>
<script id="posts-template" type="text/html">
<ul>
	<!-- ko foreach: posts -->
	  <li>
			<span data-bind="text: id"></span>, <span data-bind="text: content"></span>
			<a href="javascript:void(0)" data-bind="click: $parent.edit">edit</a>
			<a href="javascript:void(0)" data-bind="click: $parent.delete">del</a>
		</li>
	<!-- /ko -->
	<li>
		<form data-bind="submit: submit">
			<input name="content" data-bind="value: form"/>
		</form>
	</li>
</ul>
</script>
<script>
var url = '/api.php/records/posts';
function Post(id,content){
	var self = this;
	self.id = ko.observable(id);
	self.content = ko.observable(content);
}
function PostList(){
	var self = this;
	self.posts = ko.observableArray([]);
	self.form = ko.observable('');
	self.bound = false;
	self.edit = function(post) {
		var content = prompt('Value',post.content());
		if (content!==null) {
			$.ajax({url:url+'/'+post.id(), type: 'PUT', data: {content:content}, success:self.update});
		}
	};
	self.delete = function(post) {
		if (confirm("Deleting #"+post.id()+". Continue?")) {
			$.ajax({url:url+'/'+post.id(), type: 'DELETE', success:self.update});
		}
	};
	self.submit = function(form) {
		$.post(url, {user_id:1,category_id:1,content:self.form()}, self.update);
	};
	self.render = function(data) {
		var array = data.records;
		self.posts.removeAll();
		for (i=0;i<array.length;i++) {
			self.posts.push(new Post(array[i].id,array[i].content));
		}
		self.form('');
		if (!self.bound){ ko.applyBindings(self); self.bound = true; }
	};
	self.update = function() {
		$.get(url, self.render);
	};
	self.post = function() {
		$.post(url, {user_id:1,category_id:1,content:"from knockout"}, self.update);
	}
	self.post();
};
$(function(){	new PostList(); });
</script>
</head>
<body>
<div data-bind="template: { name: 'posts-template'}">Loading...</div>
</body>
</html>
